﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MediaLibraryManagement.BLL;
using MediaLibraryManagement.Entity;

namespace MediaLibraryManagement.UI
{
    public partial class UserManagement : Form
    {
        private UserBLL _business;
        private List<User> _users;
        private User _selectedUser;

        public UserManagement()
        {
            InitializeComponent();
            _business = new UserBLL();
            cboPrivilege.Enabled = false;
            chkIsActive.Enabled = false;
            btnSave.Enabled = false;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            _users = _business.Search(txtSearchText.Text);
            lstUsers.DataSource = _users;
            lstUsers.DisplayMember = "UserName";
        }

        private void lstUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            _selectedUser = _users[lstUsers.SelectedIndex];
            if (_selectedUser != null)
            {
                cboPrivilege.Enabled = true;
                chkIsActive.Enabled = true;

                txtUsername.Text = _selectedUser.UserName;
                txtJoinedDate.Text = _selectedUser.JoinedDate.ToString(@"dd/MM/yyyy");
                txtEmail.Text = _selectedUser.Email;
                cboPrivilege.SelectedItem = _selectedUser.Privilege.ToString();
                chkIsActive.Checked = _selectedUser.IsActive;
            }
            btnSave.Enabled = false;
        }

        private void cboPrivilege_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnSave.Enabled = true;
        }

        private void chkIsActive_CheckedChanged(object sender, EventArgs e)
        {
            btnSave.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            _selectedUser.Privilege = (Privileges)Enum.Parse(typeof(Privileges), cboPrivilege.SelectedItem.ToString());
            _selectedUser.IsActive = chkIsActive.Checked;
            _business.Update(_selectedUser);
            MessageBox.Show("Cập nhật người dùng thành công.");
            btnSave.Enabled = false;
        }
    }
}
